import { nextTick } from 'vue';
import { defineStore } from 'pinia';
import file from '@/utils/file/index.js'
import auth from '@/api/auth/index.js';
import users from '@/api/users/index.js';
import tools from '@/utils/tools/index.js'

const defaultAvatar = file.getStaticUrl('/avatar.png')

const defaultUserInfo = {
	gold: 0,
	money: 0,
	score: 0,
	school: {},
	nickname: '',
	avatar: defaultAvatar,
};

export const useUserStore = defineStore('user', {
	state: () => {
		return {
			chooseTopic: {},
			userInfo: defaultUserInfo,
			token: uni.getStorageSync('token'),
		};
	},

	actions: {
		async init() {
			this.token = uni.getStorageSync('token') || '';
			if (this.token) {
				return this.getUserInfo();
			}

			await this.wxOpenidLogin();
			if (this.token) {
				return this.getUserInfo();
			}

			this.userInfo = defaultUserInfo;
		},
		async getUserInfo() {
			const test = uni.$uv.test;
			const response = await users.get_user_info();
			if (response['code'] === 200) {
				const data = response['data'];
				data['money'] = tools.convertCentToYuan(data['money']);
				data['avatar'] = data['avatar'] ? file.getFileUrl(data['avatar']) : defaultAvatar;
				this.userInfo = data;
			}
		},
		async wxOpenidLogin() {
			const codeResult = await tools.getLoginCode();
			if (codeResult['code'] !== 200) return;
			const response = await auth.wx_openid_login({ code: codeResult['data'] });
			if (response['code'] === 200 && response['data']) {
				const data = response['data'];
				const token = response['data']['token'];
				uni.setStorageSync('token', token);
				this.token = token;
			}
		},
		/**
		 * @desc 校验金币
		 * @param {Number} value 消耗的金币
		 * @return {null}
		 */
		checkGold(value) {
			if (this.userInfo.gold < value) {
				uni.showModal({
					title: '提示',
					content: `亲，你的金币缺少${value - this.userInfo.gold}枚，赶紧充值一下吧。`,
					cancelColor: '#909193',
					confirmColor: '#3c9cff',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/sub/my/gold/recharge/index'
							})
						}
					}
				})
			}

			return this.userInfo.gold < value;
		}
	},
});